const WebSocket = require('ws');
const crypto = require('crypto');

// vivo大模型AppID和AppKEY
const appId = '2025579665';
const appKey = 'DWaLmGYeXmNGggPa';

// 签名算法
function getSignature(appId, timestamp, nonce, appKey) {
  const str = appId + timestamp + nonce + appKey;
  return crypto.createHash('sha256').update(str).digest('hex');
}

// 启动本地WebSocket服务器，监听8080端口
const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (clientWs, req) => {
  // 生成 vivo 鉴权参数
  const timestamp = Math.floor(Date.now() / 1000).toString();
  const nonce = Math.random().toString(36).substr(2, 8);
  const signature = getSignature(appId, timestamp, nonce, appKey);

  // 可根据前端传参自定义user_id，这里用随机生成
  const userId = crypto.randomBytes(16).toString('hex');
  const systemTime = Date.now();

  // 拼接 vivo WebSocket URL
  const wsUrl = `wss://api-ai.vivo.com.cn/asr/v2?client_version=unknown&package=unknown&sdk_version=unknown&user_id=${userId}&android_version=unknown&system_time=${systemTime}&net_type=1&engineid=shortasrinput`;

  // vivo 鉴权 header
  const headers = {
    'x-ai-gateway-app-id': appId,
    'x-ai-gateway-timestamp': timestamp,
    'x-ai-gateway-nonce': nonce,
    'x-ai-gateway-signed-headers': 'x-ai-gateway-app-id;x-ai-gateway-timestamp;x-ai-gateway-nonce',
    'x-ai-gateway-signature': signature
  };

  // 连接 vivo WebSocket
  const vivoWs = new WebSocket(wsUrl, { headers });

  // 前端 => vivo
  clientWs.on('message', (data) => {
    if (vivoWs.readyState === WebSocket.OPEN) {
      vivoWs.send(data);
    }
  });

  // vivo => 前端
  vivoWs.on('message', (data) => {
    if (clientWs.readyState === WebSocket.OPEN) {
      clientWs.send(data);
    }
  });

  // 错误和关闭处理
  clientWs.on('close', () => {
    console.log('前端WebSocket关闭');
    vivoWs.close();
  });
  clientWs.on('error', (err) => {
    console.log('前端WebSocket错误', err);
    vivoWs.close();
  });
  vivoWs.on('close', (code, reason) => {
    console.log('vivo WebSocket关闭', code, reason && reason.toString());
    clientWs.close();
  });
  vivoWs.on('error', (err) => {
    console.log('vivo WebSocket错误', err);
    clientWs.close();
  });
});

console.log('WebSocket代理服务已启动，监听端口 8080');
console.log('前端可通过 ws://localhost:8080 或 ws://192.168.43.80:8080 进行连接');
// 本地开发无需额外CORS配置，WebSocket天然支持跨域。 